import numpy as np
import matplotlib.pyplot as plt  # 2d绘图库
from sklearn.cluster import KMeans

# 读取原始数据
X = []
f = open('task3.txt', encoding='utf-8')
lineIndex = 1
for v in f:
    if lineIndex > 1:
        X.append([float(v.split()[1]), float(v.split()[2])])
    else:
        pass
    lineIndex += 1
# 转化为numpy array
X = np.array(X)

# 类簇的数量
n_clusters = 10

# 需要选手补全部分
#################################################################
# 绘制散点图


def fig_scatter(exdata, title='China'):
    plt.scatter(exdata[:, 0], exdata[:, 1], s=10)
    plt.title(title)
    plt.xlabel('经度')
    plt.ylabel('纬度')

   
fig_scatter(X)
plt.show()
 
 
# 将sklearn输出的结果变为字典形式
def trans(resu):
    redict = {}
    for ire in range(len(resu)):
        try:
            redict[resu[ire]].append(ire)
        except KeyError:
            redict[resu[ire]] = [ire]
    return redict
 
 
# 绘制算法后的类别的散点图
def sca(Xdata, signdict,
        co=['r', 'g', 'y', 'b', 'c', 'm', '#000080', '#006400','#00CED1', '#800000', '#800080',
             '#CD5C5C', '#DAA520', '#E6E6FA', '#F08080', '#FFE4C4'],
        marker=['o', '^', 'H', 's', 'd', '*', 'v', '8', 'p', 'D', 'h', '+', '1', '2', '3', '4'],
        title='China'):
    for jj in signdict:
        xdata = Xdata[signdict[jj]]
        plt.scatter(xdata[:, 0], xdata[:, -1], c=co[jj], s=20, marker=marker[jj], label='%d类' % jj)  # 绘制样本散点图
    plt.legend(bbox_to_anchor=(1.2, 1))
    plt.title(title)
    plt.xlabel('经度')
    plt.ylabel('纬度')
 
 
# Sklearn
sk = KMeans(init='k-means++', n_clusters=n_clusters, n_init=10)
 
train = sk.fit(X)
result = sk.predict(X)
skru = trans(result)
sca(X, skru, title='China')
plt.show()





#################################################

plt.title('China')
plt.show()
